
var form = document.querySelector('.container')
var input = document.querySelector('.input')
var ul = document.querySelector('.list')
var list = JSON.parse(localStorage.getItem('todolist5'))
if (list) {
    list.forEach(item => {
        addTodo(item)
    })
}
form.addEventListener('submit', (e) => {
    e.preventDefault()
    addTodo()
});

function addTodo(todo) {
    let todoText = input.value;
    if (todo) {
        todoText = todo.text;
    }
    if (todoText) {
        //拿到todo对象开始创建li元素
        const todoEL = document.createElement('li')
        //判断todo对象是否是已经完成，只有从localStorage中取出的才需要判断
        if (todo && todo.completed) {
            todoEL.classList.add('completed');
        }
        //设置节点内容
        todoEL.innerHTML = todoText
        todoEL.addEventListener('click', () => {
            todoEL.classList.toggle('completed')
            updateList()
        });
        //为节点添加contextmenu（右键单击）监听
        todoEL.addEventListener('click', (e) => {
            e.preventDefault()
            todoEL.remove();
            updateList();
        })
        //将li节点添加到ul中
        ul.appendChild(todoEL);
        input.value = ''
        // 更新
        updateList();
    }

    function updateList() {
        const list = document.querySelectorAll('li')
        const todolist = [];
        list.forEach(item => {
            todolist.push({
                text: item.innertext,
                completed: item.classList.contains('complted')
            });
        });
        localStorage.setItem('todoList5', JSON.stringify(todolist));
    }
}